package com.aisb.gis.util;

import com.alibaba.fastjson.JSONObject;
import com.sun.deploy.util.StringUtils;

import java.util.*;

public class RegionGeoHash {
    private final Double sp = 0.005;
    private String lnglats;

    public static void main(String[] args) {
        RegionGeoHash rg = new RegionGeoHash();
        rg.setLnglats(rg.regionData());
        rg.regionGeoHash();
    }

    public void regionGeoHash() {
        Map<String, Double> m = maxLnglat();
        Double maxLng = m.get("maxLng");
        Double minLng = m.get("minLng");
        Double maxLat = m.get("maxLat");
        Double minLat = m.get("minLat");

        GeoHash gh = null;
        Set<String> ghSet = new HashSet<>();
        Set<String> ghCenterSet = new HashSet<>();

        int numLng = (int) Math.round((maxLng - minLng) / sp);
        int numLat = (int) Math.round((maxLat - minLat) / sp);
        System.out.println("经度数量：" + numLng);
        System.out.println("纬度数量：" + numLat);
        for (int i = 0; i < numLng; i++) {
            System.out.println("目前进度：" + (i / numLng * 100) + "%");
            for (int j = 0; j < numLat; j++) {
                double lng = minLng + sp * i;
                double lat = minLat + sp * j;

                gh = new GeoHash(lng, lat);

                String ghnum = gh.getGeoHashBase32();
                LocationBean lb = gh.getLocation(ghnum);
                ghSet.add(ghnum);
                if (null != lb) {
                    ghCenterSet.add(lb.getLng() + "," + lb.getLat() + "," + sp * 111319.5 / 2);
                }
            }
        }

//        System.out.prin
// tln(JSONArray.toJSON(ghSet));
        System.out.println(StringUtils.join(ghCenterSet, ";"));
    }

    public Map<String, Double> maxLnglat() {
        Set lngSet = new HashSet<>();
        Set latSet = new HashSet<>();

        String[] lnglatsArr = lnglats.split(";");
        for (String lnglat : lnglatsArr) {
            String[] lnglatArr = lnglat.split(",");
            lngSet.add(Double.parseDouble(lnglatArr[0].trim()));
            latSet.add(Double.parseDouble(lnglatArr[1].trim()));
        }

        Map r = new HashMap();
        r.put("maxLng", Collections.max(lngSet));
        r.put("minLng", Collections.min(lngSet));
        r.put("maxLat", Collections.max(latSet));
        r.put("minLat", Collections.min(latSet));

        System.out.println(JSONObject.toJSON(r));

        return r;
    }


    public String regionData() {
        String lnglat = "108.9308, 34.281673; 108.978661, 34.281673; 108.978661, 34.258165; 108.9308, 34.258165;";
        return lnglat;
    }

    public String getLnglats() {
        return lnglats;
    }

    public void setLnglats(String lnglats) {
        this.lnglats = lnglats;
    }
}


